image_raw=imread("original.png");

image_hsv=rgb2hsv(image_raw);

image_h=image_hsv(:,:,1);

imwrite(image_h,"hsv_extracted.png");

image_h=imgaussfilt(image_h);
imwrite(image_h,"filtered.png");

image_bin=imbinarize(image_h);
imwrite(image_bin,"binarized.png");

% 为去除凸出部分阴影 先反片 
% 背景变为黑色
% im_r=1.*(1-image_bin);
% imwrite(im_r,"reversed.png");
% image_bin=imfill(im_r,"holes");
% imwrite(image_bin,"filled_reverse.png");
% image_bin=1.*(1-image_bin);
% imwrite(image_bin,"filled.png");

% 设置模板
template_strel = strel("square",8);
% 腐蚀掉凸出部分阴影 
% img_eroded_reverse=1-(img_eroded);
% imwrite(img_eroded_reverse,"erosion_reversed.png");
image_bin=1-imopen(image_bin,template_strel);
imwrite(image_bin,"opened.png");


% 算门槛
img=rgb2gray(imread("original.png"));
thh=otsuthresh(imhist(img));
img_b_ob=~imbinarize(img,thh);
img_ob=1.*(img_b_ob);
imwrite(img_ob,"template.png");

im_masked=image_bin.*img_b_ob;
imwrite(im_masked,"masked.png");

% 边缘检测
edges = edge(img_ob, 'Canny');

% Hough变换
[H, theta, rho] = hough(edges,"Theta",0:0.1:0.1);

% 检测峰值
P = houghpeaks(H, 10, 'threshold', 5); % 可能有多个垂直线

% 找到线条
lines = houghlines(edges, theta, rho, P, 'FillGap', 5, 'MinLength', 15);

% 过滤线条（只保留接近垂直的线条）
verticalLines = [];
for k = 1:length(lines)
    verticalLines{end+1} = lines(k);
end

% 显示左右直线结果
imshow(img_ob);hold on;
for k = 1:length(verticalLines)
    xy = [verticalLines{k}.point1; verticalLines{k}.point2];
    plot(xy(:,1), xy(:,2), 'LineWidth', 2, 'Color', 'green');
end


%命令行交互终端输出测量数值结果
distances=(verticalLines{2}.point1-verticalLines{1}.point1);
disp("左右间距为")
disp(distances(1));

